﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NFinal.Common.TaskLogger
{
    public class TextWriterTaskLogger : ITaskLogger
    {
        public string Name { get; }
        private TextWriter textWriter;
        public CancellationTokenSource CancellationTokenSource { get; }
        public TextWriterTaskLogger(TextWriter textWriter,string name=null)
        {
            this.textWriter = textWriter;
            CancellationTokenSource = new CancellationTokenSource();
            this.CancellationToken = CancellationTokenSource.Token;
            if (name == null)
            {
                this.Name = "任务";
            }
            else
            {
                this.Name = name;
            }
        }
        public CancellationToken CancellationToken { get; }
        public void LogInfo(string message)
        {
            textWriter.WriteLine(message);
        }
        public void LogError(string error)
        {
            textWriter.WriteLine(error);
        }
        public void LogExp(Exception ex)
        {
            textWriter.WriteLine(ex.Message);
            textWriter.WriteLine(ex.StackTrace);
        }
        public void LogWarn(string warn)
        {
            textWriter.WriteLine(warn);
        }
        public bool init = false;
        public void LogPercentage(double percentage, string name = null)
        {
            if (name == null)
            {
                name = Name;
            }
            if (init == false)
            {
                init = true;
                textWriter.WriteLine($"{name}进度:{Math.Round(percentage, 2)}%");
            }
            if (percentage == 100)
            {
                textWriter.WriteLine($"{name}进度:{Math.Round(percentage, 2)}%");
                init = false;
            }
            if (init)
            {
                textWriter.WriteLine($"{name}进度:{Math.Round(percentage, 2)}%");
            }
        }

        public void LogExp(Exception ex, string message)
        {
            textWriter.WriteLine(ex.Message);
            textWriter.WriteLine(ex.StackTrace);
            textWriter.WriteLine(message);
        }

        public bool CancelCurrentTask()
        {
            this.CancellationTokenSource.Cancel();
            return true;
        }
    }
}
